class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        Stack<String> stack = new Stack<>();
        int left = 0;
        for(int i = 0;i < s.length();i++) {
            if(s.charAt(i) == ' ') {
                String q = s.substring(left,i);
                stack.push(q);
                left = i+1;
                while((i+1)<s.length()&&s.charAt(i+1) == ' ') {
                    i++;
                    left = i+1;
                }
            }   
        }
        stack.push(s.substring(left,s.length()));

        StringBuilder stringBuilder = new StringBuilder();
        while(!stack.empty()) {
            stringBuilder.append(stack.pop());
            stringBuilder.append(" ");
        }
        String str = stringBuilder.substring(0,stringBuilder.length()-1);
        return str;
    }
}